// 创建用户仓库
import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogOut } from '@/api/user'
import { LoginFrom, LoginResponseData, UserInfoResponseData } from './type'
//引入数据类型
import type { UserState } from './types/type'
// 引入常量路由
import { constantRoute } from '@/router/routes'
let useUserStore = defineStore('User', {
  //存储数据
  state: (): UserState => {
    return {
      token: localStorage.getItem('TOKEN'),
      menuRoutes: constantRoute,
      userName: '',
      avatar: '',
    }
  },
  //一步|逻辑的地方
  actions: {
    // async函数会返回一个promise
    async userLogin(data: LoginFrom) {
      let result: LoginResponseData = await reqLogin(data)
      console.log(`output->result`, result)
      if (result.code == 200) {
        // console.log(`output->result.code`,result.code)
        // 登录成功 存储token
        // 由于pinia|vuex存储数据其实利用js对象，刷新页面数据丢失
        this.token = result.data as string
        // 本地存储持久化存储一份
        localStorage.setItem('TOKEN', result.data as string)
        //能保证当前async函数返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    //获取用户信息、存储到仓库中
    async getUserInfo() {
      let result: UserInfoResponseData = await reqUserInfo()
      console.log(`output->result`, result)
      if (result.code == 200) {
        this.userName = result.data.name
        this.avatar = result.data.avatar
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    async logout() {
      let result: any = await reqLogOut()
      if (result.code == 200) {
        //清除token
        this.token = ''
        localStorage.removeItem('TOKEN')
        this.userName = ''
        this.avatar = ''
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})

export default useUserStore
